package com.century.sjt.activity.setting;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.century.sjt.R;
import com.century.sjt.activity.BaseActivity;
import com.century.sjt.activity.login.ChooseCountryActivity;
import com.century.sjt.util.Base64Utils;
import com.century.sjt.util.Check;
import com.century.sjt.util.Constant;
import com.century.sjt.util.TimeButton;
import com.century.sjt.util.TipUtil;
import com.century.sjt.utils.PreferenceManager;
import com.century.sjt.widget.TitleBar.SjtTitleBar;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.HashMap;
import java.util.Map;

public class Forget_pwdActivity extends BaseActivity {

    private SjtTitleBar titleBar;
    private RequestQueue mQueue;
    private EditText NewPassword, aPhome, Number_YZ;
    private Button Btn_Subimt;
    private TimeButton getVCode;
    private String mobile, password, smsVCode;
    private Boolean isOK = false;
    private String setPwd = "";
    private LinearLayout layout_Country;
    private TextView tvCountryName, tvCountryNumber;
    private String countryNumber = "86";
    private TextView area_icon, forget_pwd_pnone_icon, forget_yzm_icon, forget_new_pwd_icon;
    private String language = PreferenceManager.getInstance().getLanguageCode();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sjt_pwd_forget);
        mQueue = Volley.newRequestQueue(this);

        if (getIntent().getExtras() != null) {
            setPwd = getIntent().getExtras().getString("setpwd");
        }

        NewPassword = (EditText) findViewById(R.id.pwdf_newpwd);
        aPhome = (EditText) findViewById(R.id.pwdf_phone);
        Number_YZ = (EditText) findViewById(R.id.pwdf_yzm);
        Btn_Subimt = (Button) findViewById(R.id.btn_pwdf_submit);
        getVCode = (TimeButton) findViewById(R.id.btn_get_pwdf_check);
        titleBar = (SjtTitleBar) findViewById(R.id.set_pwd_forget_title);
        layout_Country = (LinearLayout) findViewById(R.id.layout_country);
        tvCountryName = (TextView) findViewById(R.id.country);
        tvCountryNumber = (TextView) findViewById(R.id.country_code);
        area_icon = (TextView) findViewById(R.id.area_icon);
        forget_pwd_pnone_icon = (TextView) findViewById(R.id.forget_pwd_pnone_icon);
        forget_yzm_icon = (TextView) findViewById(R.id.forget_yzm_icon);
        forget_new_pwd_icon= (TextView) findViewById(R.id.forget_new_pwd_icon);
        Typeface iconfont=Typeface.createFromAsset(getAssets(),"iconfont.ttf");
        area_icon.setTypeface(iconfont);
        forget_pwd_pnone_icon.setTypeface(iconfont);
        forget_yzm_icon.setTypeface(iconfont);
        forget_new_pwd_icon.setTypeface(iconfont);
        tvCountryName.setText(getString(R.string.text_china));
        tvCountryNumber.setText("+86");
        getVCode.onCreate(savedInstanceState);
        checkMobile();
        initView();

    }

    //加载页面
    @Override
    protected void initView() {
        //       标题栏
        titleBar.setLeftIconResource(getResources().getString(R.string.icon_return));
        titleBar.setTitle(getResources().getString(R.string.text_forget_password));
        titleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        Btn_Subimt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (LocalValid()) {
                    forgetPassWard();
                }
            }
        });
        if (setPwd.equals("0")) {
            SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
            mobile = mainSharedPreferences.getString("mobile", "");
            aPhome.setText(mobile.substring(0, 3) + "****" + mobile.substring(mobile.length() - 4, mobile.length()));
            aPhome.setEnabled(false);
            countryNumber = mainSharedPreferences.getString("mobileCode", "");
            layout_Country.setVisibility(View.GONE);
        } else {
            mobile = aPhome.getText().toString();
        }

        getVCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                checkPhome();
                if (setPwd.equals("0")) {
                } else {
                    mobile = aPhome.getText().toString();
                }
                if (!Check.isMobileNO(mobile)) {
                    TipUtil.showToast(getResources().getString(R.string.error_phone), Forget_pwdActivity.this, 1);
                } else {

                    getVCode.setStart(true);
                    smsVcode(mobile);

                }
            }

        });

        layout_Country.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(Forget_pwdActivity.this, ChooseCountryActivity.class);
                startActivityForResult(intent, Constant.REQUESTCODE_COUNTRY);
            }
        });
    }

    @Override
    protected void initEvent() {

    }

    @Override
    protected void initData() {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode) { //resultCode为回传的标记，我在B中回传的是RESULT_OK
            case RESULT_OK:
                Bundle bundle = data.getExtras();
                String str = bundle.getString("countryName");//str即为回传的值
                String mobileCode = bundle.getString("mobileCode");
                countryNumber = mobileCode;
                tvCountryName.setText(str);
                tvCountryNumber.setText("+" + mobileCode);
                break;
            default:
                break;
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 本地验证
     */
    public Boolean LocalValid() {

//        mobile = aPhome.getText().toString();
        password = NewPassword.getText().toString();
        smsVCode = Number_YZ.getText().toString();
        if (mobile.equals("") || mobile == null) {
            TipUtil.showToast(getResources().getString(R.string.error_no_phone), Forget_pwdActivity.this, 1);
        } else if (mobile.length() != 11) {
            TipUtil.showToast(getResources().getString(R.string.error_phone), Forget_pwdActivity.this, 1);
        } else if (password.equals("") || password.length() == 0) {
            TipUtil.showToast(getResources().getString(R.string.error_no_new_password), Forget_pwdActivity.this, 1);
        } else if (!(password.length() > 5 && password.length() < 17)) {
            TipUtil.showToast(getResources().getString(R.string.error_isno_6or16_password), Forget_pwdActivity.this, 1);
        } else if (smsVCode.length() != 6) {
            TipUtil.showToast(getResources().getString(R.string.error_no_vcode), Forget_pwdActivity.this, 1);
        } else {
            isOK = true;
        }
        return isOK;
    }
    //忘记密码

    private void forgetPassWard() {

        byte[] encodePwd = password.getBytes();
        final String npwd = Base64Utils.encode(encodePwd);

        //显示Progress Dialog
        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.error_please_waitting), Forget_pwdActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.ResetPassWord, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    TipUtil.log("获取成功", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//成功
//                        JSONObject data = res.getJSONObject("data");
//                        String password = data.getString("password");
//                        Log.d("pwd",password);
//                        TipUtil.showToast(getResources().getString(R.string.reset_success), Forget_pwdActivity.this, 1);
                        if (setPwd.equals("1")) {
                            Intent intent = new Intent();
                            intent.setClass(Forget_pwdActivity.this, SettingActivity.class);
                            startActivity(intent);
                        } else {
                            finish();
                        }

                    } else {//失败
                        TipUtil.showToast(message, Forget_pwdActivity.this, 1);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service), Forget_pwdActivity.this, 1);
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), Forget_pwdActivity.this, 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
//                String userId = mainSharedPreferences.getString("userId", "");
//                map.put("loginId", userId);
                map.put("mobile", mobile.trim());
                map.put("password", npwd.trim());
                map.put("validCode", smsVCode.trim());
                map.put("mobileCode", countryNumber.trim());
                map.put("language", language);
                return map;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);
    }


    /**
     * 获取短信校验码方法
     */
    private void smsVcode(final String mobile) {

//        final String sendphone = mobile;
        //发送短信验证码至服务器进行校验
        //填写了6位数字
        getVCode.setTextAfter(getResources().getString(R.string.btn_second)).setTextBefore(getResources().getString(R.string.btn_get_verification_code)).setLenght(60 * 1000);//设置倒计时
        StringRequest regStringRequest = new StringRequest(Request.Method.POST, Constant.SendAuthCodePWd, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    TipUtil.log("获取短信校验码接口返回", response, 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//校验成功，进行注册
//                        getVCode.setStart(true);
                        getVCode.OnStart();
                        TipUtil.showToast(getResources().getString(R.string.error_smsvcode_success), Forget_pwdActivity.this, 1);
                    } else {
//                        getVCode.setStart(false);
                        TipUtil.showToast(message, Forget_pwdActivity.this, 1);
                    }
                } catch (JSONException ex) {
                    //关闭进度条
                    TipUtil.closeProgressDialog();
                    TipUtil.showToast(getResources().getString(R.string.error_service), Forget_pwdActivity.this, 1);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //关闭进度条
                TipUtil.closeProgressDialog();
                TipUtil.showToast(getResources().getString(R.string.error_network), Forget_pwdActivity.this, 1);
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();


                map.put("mobile", mobile);
                map.put("mobileCode", countryNumber.trim());
                map.put("language", language);
                return map;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(regStringRequest);
    }


    /**
     * 检测是否已经被注册了
     */
    private void checkMobile() {
        aPhome.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                checkPhome();
            }
        });

        aPhome.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                checkPhome();
            }
        });
    }

    //检测手机号
    private void checkPhome() {
        final String phone = mobile;
        if (!phone.equals("") && phone.length() == 11) {              //手机号码不为空，手机号码为11位。
            //显示Progress Dialog
//                    TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.please_waitting), RegisterActivity.this);
            String url = Constant.CheckMobileHost + mobile.toString().trim();
            StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.CheckMobileHost, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    TipUtil.log("检查手机是否注册接口返回", response, 1);
                    TipUtil.closeProgressDialog();
                    try {
                        JSONTokener jsonParser = new JSONTokener(response);
                        JSONObject res = (JSONObject) jsonParser.nextValue();
                        String code = res.getString("code");
//                                String message = res.getString("message");
//                                Toast.makeText(SjtUserLoginActivity.this, code, Toast.LENGTH_LONG).show();
                        Log.d("main", code);
                        if (code.equals("200")) {//校验不成功！
                            getVCode.setStart(true);
                        } else {
                            getVCode.setStart(false);
                            TipUtil.showToast(getResources().getString(R.string.text_phome_isno) + phone + getResources().getString(R.string.text_isno_r), Forget_pwdActivity.this, 1);

                        }
                    } catch (Exception ex) {
                        //关闭进度条
                        TipUtil.closeProgressDialog();
                        TipUtil.showToast(getResources().getString(R.string.error_service), Forget_pwdActivity.this, 1);
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    //关闭进度条
                    TipUtil.closeProgressDialog();
                    TipUtil.showToast(getResources().getString(R.string.error_network), Forget_pwdActivity.this, 1);
                }
            }) {
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    Map<String, String> map = new HashMap<String, String>();
                    SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                    String userId = mainSharedPreferences.getString("userId", "");
//            map.put("loginId", userId);
                    map.put("mobile", mobile);
                    map.put("mobileCode", countryNumber.trim());
                    return map;
                }
            };

            mQueue.add(stringRequest);
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        mQueue.cancelAll(this);
        super.onDestroy();
    }

}
